﻿using System.Collections.Generic;
using System.Configuration;
using Newtonsoft.Json;

namespace T.FAS.Runtime.DataAccess.Common
{
    public class DACLogFactory
    {
        private static readonly object s_lock = new object();
        private static readonly string s_logInfoStr = ConfigurationManager.AppSettings["ExecuteLogInfo"];
        private static readonly ExecuteLogSetting s_logInfo;
        private static readonly Dictionary<DacLogType, IDACLogService> s_cache = new Dictionary<DacLogType, IDACLogService>();

        static DACLogFactory()
        {
            if (!string.IsNullOrEmpty(s_logInfoStr))
            {
                try
                {
                    s_logInfo = JsonConvert.DeserializeObject<ExecuteLogSetting>(s_logInfoStr);
                }
                catch
                {
                    s_logInfo = LogBase.GetDefaultLogSetting();
                }
            }
            else
            {
                s_logInfo = LogBase.GetDefaultLogSetting();
            }
        }
        
        public static IDACLogService GetDACLogService()
        {
            DacLogType dacLogType = s_logInfo.LogType;
            if (!s_cache.ContainsKey(dacLogType))
            {
                lock (s_lock)
                {
                    if (!s_cache.ContainsKey(dacLogType))
                    {
                        IDACLogService logService;
                        if (dacLogType == DacLogType.Local)
                            logService = new LocalLog();
                        else
                            logService = new BigDataLog();
                        s_cache[dacLogType] = logService;
                    }
                }
            }
            return s_cache[dacLogType];
        }

        private static ExecuteLogSetting GetDefaultLogSetting()
        {
            return new ExecuteLogSetting
            {
                IsLog = true,
                LogType = DacLogType.LogService,
                IsLogError = true,
                IsLogSQL = true,
            };
        }
    }
}